<?php
/**
 * tinymvc超轻量级PHP开发框架
 *
 * @author    Lansn
 * @copyright Copyright (c) 2024-2025
 * @license   tinymvc 遵循Apache2开源协议发布，需保留开发者信息。
 * @link      http://173654757.xyz
 */

namespace tinymvc\core;

class Model extends \flight\ActiveRecord
{
    protected static $pdoInstances = [];

    public function __construct(?string $table = null, array $options = [], ?string $driver = null)
    {
        static $dbConfig = null;

        if ($dbConfig === null) {
            $dbConfig = include ROOT_PATH . 'config/database.php';
        }

        // 获取默认连接驱动
        $driver = $driver ?: ($dbConfig['default'] ?? 'mysql');

        // 从 connections 中取配置
        if (!isset($dbConfig['connections'][$driver])) {
            throw new \Exception("No database configuration found for driver: {$driver}");
        }

        $connection = $dbConfig['connections'][$driver];

        // 尝试复用 PDO 实例
        if (isset(self::$pdoInstances[$driver])) {
            $pdo = self::$pdoInstances[$driver];
        } else {
            switch ($connection['type']) {
                case 'sqlite':
                    $dsn = "sqlite:{$connection['database']}";
                    $pdo = new \PDO($dsn);
                    break;

                case 'pgsql':
                case 'mysql':
                    $dsn = sprintf(
                        '%s:host=%s;port=%s;dbname=%s;charset=%s',
                        $connection['type'],
                        $connection['hostname'],
                        $connection['hostport'] ?? ($connection['type'] === 'pgsql' ? 5432 : 3306),
                        $connection['database'],
                        $connection['charset'] ?? 'utf8mb4'
                    );
                    $pdo = new \PDO($dsn, $connection['username'], $connection['password']);
                    break;

                default:
                    throw new \Exception("Unsupported database type: {$connection['type']}");
            }

            $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            self::$pdoInstances[$driver] = $pdo;
        }

        parent::__construct($pdo, $table, $options);
    }
}
